//
//  MCHomePageViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/18.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit


class MCHomePageViewController: MCViewController {
    
    var dataArray : NSArray = NSArray()
    
    // 店长展示的UI
    let managerArray : NSArray = [
        ["title":"订单信息","items":[#imageLiteral(resourceName: "Home_order_one"),#imageLiteral(resourceName: "Home_order_two")]],
        ["title":"商品","items":[#imageLiteral(resourceName: "Home_goods_one"),#imageLiteral(resourceName: "Home_goods_two"),#imageLiteral(resourceName: "Home_goods_three")]],
        ["title":"店铺管理","items":[#imageLiteral(resourceName: "Home_store_one"),#imageLiteral(resourceName: "Home_store_two"),#imageLiteral(resourceName: "Home_store_three"),#imageLiteral(resourceName: "Home_store_four")]],
    ]
    
    // 店员的UI
    let assistantArray : NSArray = [
        ["title":"订单信息","items":[#imageLiteral(resourceName: "Home_order_one")]],
        ["title":"商品","items":[#imageLiteral(resourceName: "Home_goods_one")]],
        ["title":"店铺管理","items":[#imageLiteral(resourceName: "Home_store_one")]],
    ]
    
    // 分销员的UI
    let salesStaffArray : NSArray = [
        ["title":"订单信息","items":[#imageLiteral(resourceName: "Home_order_one")]],
        ["title":"商品","items":[#imageLiteral(resourceName: "Home_goods_one")]],
        ["title":"店铺管理","items":[#imageLiteral(resourceName: "Home_store_one")]],
    ]

    
    deinit {
        MCNotification_remove(vc: self, name: NOTIFICATION_ChangeStore)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        // 根据用户权限，改变UI
        accordingToThePermissionToChangeTheUI()

        managerClosure()

        sendNetworking()
        
    }
    
    // MARK: - Setter & Getter
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(19)
        label.text = MCSystem_APPName
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.white
        label.frame = CGRect.init(x: 0, y: 0, width: 100, height: 44)
        return label
    }()
    
    lazy var topBgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCMain
        return view
    }()
    
    private lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray.init()
        return arrayM
    }()
    
    lazy var storeinfoView: MCHomePage_storeinfoView = {
        let view = MCHomePage_storeinfoView()

        return view
    }()
    
    lazy var promptImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "Home_prompt")
        imageView.contentMode = UIViewContentMode.center
        imageView.frame = CGRect.init(x: 0, y: 0, width: MCScreenWidth, height: 50)
        return imageView
    }()
}

//MARK: 通知回调，闭包回调，点击事件
extension MCHomePageViewController {
    // MARK: - Block
    func managerClosure() {
        self.storeinfoView.closure = {vc in
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: false)
        }
    }
    
    // MARK: - Action
    // 云支付
    @objc func sweepPayClicked() {
    
        let vc = MCSweepPayViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: false)
    }
    
    @objc func rightItemClicked() {
        let vc = MCScanViewController()
        vc.scanType = MCScanType.orderScan
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: false)
    }
    
    @objc func changeStoreEvent() {
        sendNetworking()
        accordingToThePermissionToChangeTheUI()
    }
    
    @objc func notification_pushTo(not:NSNotification) {
        let object = not.object as? [String : Any] ?? [:]
        let value = object["jumpType"] as? Int ?? 0
        
        let vc = MCDiscountPayViewController()
        vc.type = value
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}


//MARK: 网络请求
extension MCHomePageViewController {
    
    // MARK: - Network
    func sendNetworking() {
        
        // 店铺信息
        MCNetwork.POST(JAVA_storeInformation, nil, vc: self, success: { (data) in
            self.storeinfoView.dataDict = data.dictionaryObject ?? [:]
        }, failure: nil)
        
        
        // 版本更新接口
        let para = [
            "type" : "1",
            "versionType" : "bapp",
            "versionCode" : MCSystem_APPVersion
            ] as [String : Any]
        MCNetwork.POST(JAVA_getVersionInfo, para, vc: self, success: { (data) in
            
            let dataDict = data.dictionaryObject ?? [:]
            
            
            let forcedUpdate = dataDict["forcedUpdate"] as? NSNumber ?? 0
            let description = dataDict["description"] as? String ?? ""
            
            if forcedUpdate.intValue == 1 {  // 是否强制更新
                MCAlterController_oneOptions(vc: self, message: description, cancle: {
                    let downloadUrl = MCWords_appId
                    let nsStringToOpen = "itms-apps://itunes.apple.com/cn/app/id\(downloadUrl)?mt=8"
                    UIApplication.shared.openURL(URL.init(string: nsStringToOpen)!)
                })
            }
        }, failure: nil)
    }
}

//MARK: UI的处理
extension MCHomePageViewController {
   
    func baseSetting() {
        self.navigationItem.titleView = titleLabel
        self.view.backgroundColor = UIColor.white

        
        navigationBarBackgroundImage = UIImage.init(color: UIColor.MCMain)
        navigationBarLineHidden = true
        
        
        // 分销员没云支付的功能
        if MCUserinfo_getLevel() > MCRole_salesStaff {
            navigationItem.leftBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Home_pay"), target: self, selector: #selector(sweepPayClicked),isLeft: true)
        } else {
            self.navigationItem.leftBarButtonItem = nil
        }
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Home_scan"), target: self, selector: #selector(rightItemClicked))
        
        
        MCNotification_addObserver(name: MCNotification_Jpush, vc: self, selector: #selector(notification_pushTo(not:)))
        
        
        MCNotification_addObserver(name: NOTIFICATION_ChangeStore, vc: self, selector: #selector(changeStoreEvent))
    }

    
    func initUI() {
        
        view.addSubview(topBgView)
        topBgView.snp.remakeConstraints { (make) ->Void in
            make.left.top.right.equalTo(view)
            make.height.equalTo(250)
        }
        
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
        
        tableView.tableHeaderView = storeinfoView
        tableView.tableFooterView = promptImageView
    }
    
    
    func accordingToThePermissionToChangeTheUI() {
        if MCUserinfo_getLevel() >= MCRole_manager {
            dataArray = managerArray
        } else if MCUserinfo_getLevel() == MCRole_assistant {
            dataArray = assistantArray
        } else {
            dataArray = salesStaffArray
        }
        tableView.reloadData()
    }
}



//MARK: 代理
extension MCHomePageViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let dict = dataArray[section] as? [String:Any] ?? [:]
        
        let array = dict["items"] as? NSArray ?? []
        let count = array.count
        
        return count % 2 == 0 ? (count / 2) : (count / 2 + 1)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let dict = dataArray[section] as? [String:Any] ?? [:]
        let title = dict["title"] as? String ?? ""
        
        
        let view = MCHomePageSectionHeadView()
        view.titleLabel.text = title
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 7
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return MCScreenWidth / 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let dict = dataArray[indexPath.section] as? [String:Any] ?? [:]
        
        let items = dict["items"] as? NSArray ?? []
        
        let cell = MCHomePageCell.customCell(tableView: tableView)
        
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        cell.indexPath = indexPath
        
        if (indexPath.row == 0) {
            if (items.count > 0) {
                cell.leftButton.setImage(items[0] as? UIImage, for: .normal)
            }
            
            if (items.count > 1) {
                cell.rightButton.setImage(items[1] as? UIImage, for: .normal)
            }
        } else {
            let index = indexPath.row * 2
            if (items.count > index) {
                cell.leftButton.setImage(items[index] as? UIImage, for: .normal)
            }
            
            if (items.count  > index + 1) {
                cell.rightButton.setImage(items[index + 1] as? UIImage, for: .normal)
            }
        }

        
        cell.closure = { vc in
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: false)
        }
        
        return cell
    }
}


